package com.nna.videoplayer;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TableLayout;
import android.widget.TextView;

public class VideoPlayer extends Activity {
	String fileVideo = "/mnt/sdcard/test.mp4";
	View mHideContainer;
	View mControlPanelContainer;
	View imgPlay; 
	View imgBackward;
	View imgForward;
	View imgAspectRatio;
	SeekBar mSeekBar;
	TextView currentTime; 
	TextView totalTime; 
	TableLayout controlPanel;
	
	private Handler mHandler = new Handler();
	private Updater seekBarUpdater = new Updater();
	
	
	long totalDuration;

	DemoRenderer demoRenderer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Globals.setNativeVideoPlayer(false);
        log("Video Player Created");
        
        // fullscreen mode
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		
		setContentView(R.layout.video_player);
        

		Globals.setFileName(fileVideo);
		// Find the views whose visibility will change
		mSeekBar = (SeekBar) findViewById(R.id.progressbar);
		currentTime = (TextView) findViewById(R.id.currenttime);     
		totalTime = (TextView) findViewById(R.id.totaltime);        
		controlPanel = (TableLayout) findViewById(R.id.controlPanel);
		controlPanel.getBackground().setAlpha(85);
		imgPlay = findViewById(R.id.img_vp_play);
		imgForward = findViewById(R.id.img_vp_forward);
		imgBackward = findViewById(R.id.img_vp_backward);
		imgAspectRatio = findViewById(R.id.fs_shadow);
		mHideContainer = findViewById(R.id.hidecontainer);
		mHideContainer.setOnClickListener(mVisibleListener);
		mControlPanelContainer = findViewById(R.id.controlPanel);
		imgAspectRatio.setOnTouchListener(imgAspectRatioTouchListener);
		imgPlay.setOnTouchListener(imgPlayTouchListener);
		imgForward.setOnTouchListener(imgForwardTouchListener);
		imgBackward.setOnTouchListener(imgBackwardTouchListener);
		mSeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener);
		initSDL();
		
    }
    public void initSDL(){
		//Wake lock code

		//Native libraries loading code
		Globals.LoadNativeLibraries();
		log("native libraries loaded");

//		//Audio thread initializer
//		mAudioThread = new AudioThread(this);
		log("Skip Audio thread initialized");

		GLSurfaceView_SDL surfaceView = (GLSurfaceView_SDL) findViewById(R.id.glsurfaceview);
		log("got the surface view:");

		surfaceView.setOnClickListener(mGoneListener);

		DemoRenderer demoRenderer = new DemoRenderer(this);
		this.demoRenderer = demoRenderer;
		surfaceView.setRenderer(demoRenderer); 
		log("Set the surface view renderer");

		SurfaceHolder holder = surfaceView.getHolder();
		holder.addCallback(surfaceView);
		log("Added the holder callback");
		holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
		log("Hold type set");

		surfaceView.setFocusable(true);
		surfaceView.requestFocus();

		mHandler.postDelayed(seekBarUpdater, 100);
		//totalDuration = demoRenderer.nativePlayerTotalDuration();
		//totalTime.setText(Utils.formatTime(totalDuration));
		
	}
    OnClickListener mGoneListener = new OnClickListener() 
	{
		public void onClick(View v) 
		{
			log("Inside mGone Click");
			if ((mHideContainer.getVisibility() == View.INVISIBLE) ||
					(mHideContainer.getVisibility() == View.GONE))
			{
				mHideContainer.setVisibility(View.VISIBLE);
				restartUpdater();
			}	else 
			{
				mHideContainer.setVisibility(View.INVISIBLE);
				seekBarUpdater.stopIt();
			}
		}
	};
    OnSeekBarChangeListener mSeekBarChangeListener = new OnSeekBarChangeListener() {
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
//			//System.out.println("Should be visible:" + trScrolledTime.getVisibility());
//			//trScrolledTime.setVisibility(View.GONE);
//			//trScrolledTime.setVisibility(View.INVISIBLE);
//			//System.out.println("Should be gone:" + trScrolledTime.getVisibility());
//
//			int progress = seekBar.getProgress();
//			//System.out.println("Seeked to new progress" + (float) (progress / 10F ));
//			//System.out.println("Progress new:"+progress);
//			demoRenderer.nativePlayerSeek(progress);
//			if (!paused) {
//				restartUpdater();
//			} 
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			//	// TODO Auto-generated method stub
			//	trScrolledTime.setVisibility(View.VISIBLE);
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			// TODO Auto-generated method stub
			//System.out.println("Progress Changed = " + progress);
			//System.out.println("Progres change percent=" + (float) (progress / 10F ));				
			if(fromUser) {
				long currentSecsMoved = (long)((totalDuration * ((float) (progress / 10F ))) / 100);
				String timeMoved = Utils.formatTime(currentSecsMoved);
				//scrolledtime.setText(timeMoved);
				currentTime.setText(timeMoved);
				//resetAutoHider();
			}
		}
	};
    OnTouchListener imgBackwardTouchListener = new OnTouchListener() {			
		@Override
		public boolean onTouch(View v, MotionEvent event) {
//			ImageView img = (ImageView) v;
//			if (event.getAction() == MotionEvent.ACTION_DOWN ) {		            		            
//				img.setImageResource(R.drawable.vp_backward_glow_80x60);
//			}
//			else if (event.getAction() == MotionEvent.ACTION_UP ) {		        	
//				img.setImageResource(R.drawable.vp_backward);										
//				demoRenderer.nativePlayerRewind();
//			}						
//			//resetAutoHider();
			return true;
		}
	};
    OnTouchListener imgForwardTouchListener = new OnTouchListener() {			
		@Override
		public boolean onTouch(View v, MotionEvent event) {
//			ImageView img = (ImageView) v;
//			if (event.getAction() == MotionEvent.ACTION_DOWN ) {		            		            
//				img.setImageResource(R.drawable.vp_forward_glow);
//			}
//			else if (event.getAction() == MotionEvent.ACTION_UP ) {		        	
//				img.setImageResource(R.drawable.vp_forward);										
//				demoRenderer.nativePlayerForward();
//			}							
//			//resetAutoHider();
			return true;
		}
	};
    OnTouchListener imgPlayTouchListener = new OnTouchListener() {			
		@Override
		public boolean onTouch(View v, MotionEvent event) {
//			ImageView img = (ImageView) v;				
//			if (event.getAction() == MotionEvent.ACTION_DOWN ) {	
//				System.out.println("Down paused:" + paused);
//				if(paused) {
//					img.setImageResource(R.drawable.vp_play);
//				}
//				else {
//					img.setImageResource(R.drawable.vp_pause);
//				}
//			}
//			else if (event.getAction() == MotionEvent.ACTION_UP ) {
//				System.out.println("Up paused:" + paused);		  
//				System.out.println("Total:" + demoRenderer.nativePlayerTotalDuration() + "---Current:" + demoRenderer.nativePlayerDuration());
//				if(paused) {
//					demoRenderer.nativePlayerPause();
//					seekBarUpdater = new Updater();
//					mHandler.postDelayed(seekBarUpdater, 500);
//					img.setImageResource(R.drawable.vp_pause_shadow);
//				}
//				else {
//					demoRenderer.nativePlayerPlay();
//					seekBarUpdater.stopIt();						
//					img.setImageResource(R.drawable.vp_play_shadow);
//				}		        	
//				paused = !paused;
//			}				
			//resetAutoHider();
			return true;
		}
	};
    OnTouchListener imgAspectRatioTouchListener = new OnTouchListener() {			
		@Override
		public boolean onTouch(View v, MotionEvent event) {
//			ImageView img = (ImageView) v;
//			if (event.getAction() == MotionEvent.ACTION_DOWN) {
//				//Do nothing for now
//			}
//			else if (event.getAction() == MotionEvent.ACTION_UP) {
//				if (current_aspect_ratio_type == 3) {
//					img.setImageResource(R.drawable.fs_shadow_4_3);
//					demoRenderer.nativePlayerSetAspectRatio(0);
//					current_aspect_ratio_type = 1;
//				} else if (current_aspect_ratio_type == 1) {
//					img.setImageResource(R.drawable.fs_shadow);
//					demoRenderer.nativePlayerSetAspectRatio(3);
//					current_aspect_ratio_type = 2;
//				} else if (current_aspect_ratio_type == 2) {
//					img.setImageResource(R.drawable.fs_shadow_16_9);
//					demoRenderer.nativePlayerSetAspectRatio(2);
//					current_aspect_ratio_type = 3;
//
//				}
//			}						
//			//resetAutoHider();
			return true;
		}
	};
    private void log(String ss){
    	Log.d("nna-videoplayer",ss);
    }
   
    OnClickListener mVisibleListener = new OnClickListener() 
	{
		public void onClick(View v) 
		{
			if ((mHideContainer.getVisibility() == View.GONE) ||(mHideContainer.getVisibility() == View.INVISIBLE)){
				mHideContainer.setVisibility(View.VISIBLE);
				restartUpdater();
			} else 	{
				mHideContainer.setVisibility(View.INVISIBLE);
				seekBarUpdater.stopIt();
			}
		}
	};
	public void restartUpdater() {
		seekBarUpdater.stopIt();
		seekBarUpdater = new Updater();
		mHandler.postDelayed(seekBarUpdater, 100);
	}
	
	private class Updater implements Runnable {
		private boolean stop;
		public void stopIt() {
			log("Stopped updater");
			stop = true;
		}

		@Override
		public void run() {
			//Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
//			if(currentTime != null && demoRenderer != null) {
//				long playedDuration = demoRenderer.nativePlayerDuration();				
//				currentTime.setText(Utils.formatTime(playedDuration));
//				totalDuration = demoRenderer.nativePlayerTotalDuration();
//				if(totalDuration != 0) {
//					int progress = (int)((1000 * playedDuration) / totalDuration);
//					mSeekBar.setProgress(progress);							
//					totalTime.setText(Utils.formatTime(totalDuration));
//				}						
//				if (demoRenderer.fileInfoUpdated) {
//					//if (Globals.fileName != null) {
//					//	videoInfo.setText(FileManager.getFileName(Globals.fileName));
//					//}
//					demoRenderer.fileInfoUpdated = false;
//				}
//			}

			if(!stop) {
				if (Globals.fileName != null) {
					//Restart the updater if file is still playing
					mHandler.postDelayed(seekBarUpdater, 500);
				}
			}
		}
	}
}
